package com.zhiqianbao.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.creditx.xbehavior.sdk.ActionName;
import com.creditx.xbehavior.sdk.CreditXAgent;
import com.creditx.xbehavior.sdk.PageName;
import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.adapter.NiceSpinner;
import com.zhiqianbao.entity.PhoneContact;
import com.zhiqianbao.entity.UserBank;
import com.zhiqianbao.entity.UserInfo;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.DialogTypeUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.TimeStatisticsUtil;
import com.zhiqianbao.view.ClearEditText;
import com.zhiqianbao.view.ProcessProgressBarView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

import static com.zhiqianbao.R.id.marray_cheack;

/**
 * Created by 子龙 on 2017/4/12.
 * 申请贷款第四步
 */

public class ThirdActivity extends BaseActivity implements View.OnClickListener {

    //银行卡号
    private EditText edit_firstId_BankCategory;
    private Gson gson = new Gson();
    //下一步按钮
    private Button button_firstIDAuthenActivity_OK_one;
    //选择银行
    private EditText edit_firstId_BankCategory_id;
    //选择城市
    private EditText edit_firstId_credit;
    private EditText edit_provice_text;
    private EditText edit_area_text;
    private EditText edit_city_text;

    private EditText edit_firstId_contactName;
    private ImageView iv_relative;
    //所属银行
    private EditText edit_firstId_BankAddress;
    private ClearEditText put_phone;
    private RadioGroup radioGroup_sex_id;
    private RadioButton marray_no;
    SharedPreferanceUtils sharedPreferanceUtils;
    //已婚按钮
//    private Spinner marry_yes1;
    //未婚
//    private Spinner marry_no1;
    private ImageView iv_relative1;
    private EditText edit_second_contactName;
    private ClearEditText put_phone2;
    private TextView topbar_textview_title;
    private Button button_return;
    private int number = 2;
    private String selectText;
    //第二个关系
    private NiceSpinner marry_yes3;
    private String selectRaltion;
    private NiceSpinner marry_no1;
    private TextView marry_yes1;
    private String firstretion;
    private List<String> dataset;
    private String relative;
    private DialogTypeUtils typeUtils;
    ProcessProgressBarView processView;
    private String trim;
    private String startTimes="";
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //统计进入联系人页面开始时间
        startTimes=TimeStatisticsUtil.getTime();
        setContentView(R.layout.activity_third);
        initView();
        initData();
        addListner();
        typeUtils = new DialogTypeUtils(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        CreditXAgent.onEnteringPage(PageName.CONTACTS_INFO);
    }

    @Override
    public void onPause() {
        super.onPause();
        CreditXAgent.onLeavingPage(PageName.CONTACTS_INFO);
    }

    private void initData() {


        //第一个关系
        marry_no1.setTextColor(Color.GRAY);
        dataset = new LinkedList<>(Arrays.asList("父亲", "母亲"));
        marry_no1.attachDataSource(dataset);
        firstretion = "配偶";


        //第二个关系
        marry_yes3.setTextColor(Color.GRAY);
        if (trim.equals(firstretion)){
            List<String> dataset1 = new LinkedList<>(Arrays.asList("父亲", "母亲", "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
            marry_yes3.attachDataSource(dataset1);
        }
//        List<String> dataset1 = new LinkedList<>(Arrays.asList("父亲", "母亲", "配偶", "子女", "兄弟", "姐妹", "其它亲属 ", "朋友", "同事"));

//        selectRaltion = marry_yes3.getText().toString().trim();

    }

    private void addListner() {
        edit_firstId_BankAddress.setOnClickListener(this);
        edit_firstId_credit.setOnClickListener(this);
        iv_relative.setOnClickListener(this);
        iv_relative1.setOnClickListener(this);
        button_return.setOnClickListener(this);
        button_firstIDAuthenActivity_OK_one.setOnClickListener(this);
    }

    private void initView() {
        sharedPreferanceUtils = new SharedPreferanceUtils(this);
        edit_firstId_BankCategory = (EditText) findViewById(R.id.edit_firstId_BankCategory);

        SharedPreferanceUtils.getEmergency();

        //联系人姓名1
        edit_firstId_contactName = (EditText) findViewById(R.id.edit_firstId_contactName);
        String contact = edit_firstId_contactName.getText().toString().trim();
        //输入手机号1
        put_phone = (ClearEditText) findViewById(R.id.put_phone);
        String phone1 = put_phone.getText().toString().trim();
        //联系人姓名
        edit_second_contactName = (EditText) findViewById(R.id.edit_second_contactName);
        String contact2 = edit_second_contactName.getText().toString().trim();
        button_firstIDAuthenActivity_OK_one = (Button) findViewById(R.id.button_firstIDAuthenActivity_OK_one);
        edit_firstId_BankCategory_id = (EditText) findViewById(R.id.edit_firstId_BankCategory_id);
        edit_firstId_BankAddress = (EditText) findViewById(R.id.edit_firstId_BankAddress);
        edit_provice_text = (EditText) findViewById(R.id.edit_provice_text);
        edit_area_text = (EditText) findViewById(R.id.edit_area_text);
        edit_city_text = (EditText) findViewById(R.id.edit_city_text);
        marry_no1 = (NiceSpinner) findViewById(R.id.marry_no1);
        selectText = marry_no1.getText().toString().trim();
        //下拉
        marry_yes1 = (TextView) findViewById(R.id.marry_yes1);
        trim = marry_yes1.getText().toString().trim();


        edit_firstId_credit = (EditText) findViewById(R.id.edit_firstId_credit);

        marry_yes1.setEnabled(false);
        marry_yes1.setVisibility(View.VISIBLE);

        marry_no1.setVisibility(View.INVISIBLE);


        iv_relative = (ImageView) findViewById(R.id.iv_relative);



        radioGroup_sex_id = (RadioGroup) findViewById(R.id.radioGroup_sex_id);
        marray_no = (RadioButton) findViewById(R.id.marray_no);


        //联系人二
        iv_relative1 = (ImageView) findViewById(R.id.iv_relative1);
        //联系人手机号2
        put_phone2 = (ClearEditText) findViewById(R.id.put_phone2);
        String phone2 = put_phone2.getText().toString().trim();

        topbar_textview_title = (TextView) findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("首次信息确认");
        //返回按钮
        button_return = (Button) findViewById(R.id.button_return);
        //第二个联系人关系
        marry_yes3 = (NiceSpinner) findViewById(R.id.marry_yes3);
        processView= (ProcessProgressBarView) findViewById(R.id.process_layout);
        //芝麻开启状态,1开启，0未开启
        String zhimaOpenOrClose = sharedPreferanceUtils.getZhimaOpenOrClose();
        if("1".equals(zhimaOpenOrClose)){
            processView.openZhiMaProcess(ProcessProgressBarView.IS_SHOW_ZHIMA,4);
        }
        else{
            processView.openZhiMaProcess(ProcessProgressBarView.NOTIS_SHOW_ZHIMA,3);
        }
        if (trim.equals("配偶")){
            List<String> dataset2 = new LinkedList<>(Arrays.asList("父亲","母亲", "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
            marry_yes3.attachDataSource(dataset2);
            sharedPreferanceUtils.setPo("配偶");
        }
        selectRaltion = "父亲";
        sharedPreferanceUtils.setRelation(selectRaltion);
//        if (firstretion.equals("母亲")){
//            List<String> dataset2 = new LinkedList<>(Arrays.asList("父亲", "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
//            marry_yes3.attachDataSource(dataset2);
//        }
        marry_no1.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                firstretion = dataset.get(position);
                if (firstretion.equals("母亲")){
                    List<String> dataset2 = new LinkedList<>(Arrays.asList("父亲",  "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
                    marry_yes3.attachDataSource(dataset2);
                }
                if (firstretion.equals("父亲")){
                    List<String> dataset2 = new LinkedList<>(Arrays.asList("母亲", "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
                    marry_yes3.attachDataSource(dataset2);
                }
                if (firstretion.equals("配偶")){
                    List<String> dataset2 = new LinkedList<>(Arrays.asList("母亲", "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
                    marry_yes3.attachDataSource(dataset2);
                }
                sharedPreferanceUtils.setFather(firstretion);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        marry_yes3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //拿到选的值
                try {
                    selectRaltion = (String) parent.getItemAtPosition(position - 1);
                    Log.i("关系..2", selectRaltion);
                    sharedPreferanceUtils.setRelation(selectRaltion);
                } catch (Exception e) {

                }


            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        radioGroup_sex_id.setOnCheckedChangeListener(listen);


        edit_firstId_contactName.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.CONTACT_INFO_CONTACT_1_NAME));
        put_phone.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.CONTACT_INFO_CONTACT_1_PHONE));
        edit_second_contactName.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.CONTACT_INFO_CONTACT_2_NAME));
        put_phone2.addTextChangedListener(CreditXAgent
                .createTextWatcher(ActionName.Input.CONTACT_INFO_CONTACT_2_NAME));

    }

    RadioGroup.OnCheckedChangeListener listen = new RadioGroup.OnCheckedChangeListener()

    {

        @Override
        public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
            int id = group.getCheckedRadioButtonId();
            if(marray_cheack==group.getCheckedRadioButtonId()){
                    number = 2;

                    //已婚
                    marry_yes1.setVisibility(View.VISIBLE);
                    marry_no1.setVisibility(View.INVISIBLE);
                    firstretion = "配偶";
                    if (firstretion.equals("配偶")) {
                        List<String> dataset2 = new LinkedList<>(Arrays.asList("父亲", "母亲", "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
                        marry_yes3.attachDataSource(dataset2);
                        sharedPreferanceUtils.setPo(firstretion);
                    }
            }
            else if(R.id.marray_no==group.getCheckedRadioButtonId()){
                    firstretion = "父亲";
                    selectRaltion = "母亲";
                    sharedPreferanceUtils.setFather(firstretion);
                    sharedPreferanceUtils.setRelation(selectRaltion);
                    number = 1;

                    //未婚
                    marry_no1.setVisibility(View.VISIBLE);
                    marry_yes1.setVisibility(View.INVISIBLE);
                    firstretion = marry_no1.getText().toString().trim();
                    if (firstretion.equals("父亲")){
                        List<String> dataset2 = new LinkedList<>(Arrays.asList("母亲", "子女", "兄弟", "姐妹", "其他亲属 ", "朋友", "同事"));
                        marry_yes3.attachDataSource(dataset2);
                    }
            }
        }
    };


    @Override
    public void onClick(View v) {
        if (R.id.button_firstIDAuthenActivity_OK_one == v.getId()) {
            if (StringUtils.isBlank(edit_firstId_BankCategory.getText().toString().trim())
                    || StringUtils.isBlank(edit_firstId_BankAddress.getText().toString().trim())
                    || StringUtils.isBlank(edit_firstId_credit.getText().toString().trim())
                    || StringUtils.isBlank(edit_firstId_contactName.getText().toString().trim())
                    || StringUtils.isBlank(put_phone.getText().toString().trim())
                    || StringUtils.isBlank(edit_second_contactName.getText().toString().trim())
                    ) {
                showShortToast1("信息要填写完整哦");
                return;
            }
            String backnumber = edit_firstId_BankCategory.getText().toString().trim();
            sharedPreferanceUtils.setBacnNumber(backnumber);

            //所属银行

            String banckaddress = edit_firstId_BankAddress.getText().toString().trim();
            sharedPreferanceUtils.setBanckName(banckaddress);
            //开户城市

            String city = edit_firstId_credit.getText().toString().trim();
            sharedPreferanceUtils.setCity(city);
            // 联系人姓名1
            edit_firstId_contactName = (EditText) findViewById(R.id.edit_firstId_contactName);
            String contact = edit_firstId_contactName.getText().toString().trim();
            if (fasterClickCheck())
                return;
            try {
//                    showWaitDialog();
                Map<String, String> param = new HashMap<>();
                param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                param.put("bankId", edit_firstId_BankCategory_id.getText().toString().trim());
                param.put("bankCard", edit_firstId_BankCategory.getText().toString().trim());
                param.put("bankProvince", edit_provice_text.getText().toString().trim());
                param.put("bankCity", edit_area_text.getText().toString().trim());
                param.put("bankArea", edit_city_text.getText().toString().trim());
                param.put("marriage", number + "");
                param.put("urgentPhone1", put_phone.getText().toString().trim());
                param.put("urgentName1", contact);
                param.put("relationship1", firstretion);
                param.put("urgentPhone2", put_phone2.getText().toString().trim());
                param.put("urgentName2", edit_second_contactName.getText().toString().trim());
                param.put("relationship2", selectRaltion);
                param.put("mimidaiVersion", Constants.APP_VERSION);
                param.put("mimidaiCode", Constants.APP_CODE + "");
                param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");

                //添加时间统计
                String endTime = TimeStatisticsUtil.getTime();
                param.put("startTime", startTimes);
                param.put("endTime", endTime);

                new FirstSaveUserInfo1().execute(param);
            } catch (NullPointerException e) {
                return;// Constants.LOGIN_USER会出现空指针异常
            }
        } else if (R.id.edit_firstId_BankAddress == v.getId()) {
            //所属银行
            hideSoftInfput(edit_firstId_BankAddress);
            alertBankSelectDialog(edit_firstId_BankAddress, edit_firstId_BankCategory_id);
        } else if (R.id.edit_firstId_BankCategory == v.getId()){
        //
        }
        else if(R.id.edit_firstId_credit==v.getId()) {
        //开户城市
            hideSoftInfput(edit_firstId_credit);
            if (typeUtils != null) {
                if ((typeUtils.getOptions1Items() != null && (typeUtils.getOptions1Items().size() != 0)) &&
                        (typeUtils.getOptions2Items() != null && (typeUtils.getOptions2Items().size() != 0)) &&
                        (typeUtils.getOptions3Items() != null && (typeUtils.getOptions3Items().size() != 0))) {
                    typeUtils.showPickerView(edit_firstId_credit, edit_provice_text, edit_area_text, edit_city_text);
                } else {
                    typeUtils.initJsonData(this);
                    typeUtils.showPickerView(edit_firstId_credit, edit_provice_text, edit_area_text, edit_city_text);
                }
            }
        }
        else if(R.id.iv_relative==v.getId()) {
                //输入联系人
                CreditXAgent.onClick(ActionName.Click.CONTACT_INFO_CONTACT_1_FROM_ADDRESS_BOOK);
                Intent contactsMobileIntent = new Intent(ThirdActivity.this, ContactsMobileActivity.class);
                contactsMobileIntent.putExtra("edit", "0");
                startActivityForResult(contactsMobileIntent, 1);
        }
        else if(R.id.iv_relative1==v.getId()) {
                //输入联系人
                CreditXAgent.onClick(ActionName.Click.CONTACT_INFO_CONTACT_2_FROM_ADDRESS_BOOK);
                Intent contactsMobileIntent2 = new Intent(ThirdActivity.this, ContactsMobileActivity.class);
                contactsMobileIntent2.putExtra("edit", "0");
                startActivityForResult(contactsMobileIntent2, 2);
        }
        else if(R.id.button_return==v.getId()){
                finish();
        }

    }

    /**
     * 隐藏软键盘
     */
    public void hideSoftInfput(EditText myEditText){
        InputMethodManager imm = (InputMethodManager)getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }


        switch (requestCode) {
            //选择联系人
            case 1:
                PhoneContact phoneContact = (PhoneContact) data.getSerializableExtra("phone");
                put_phone.setText(phoneContact.getPhoneNum());
                edit_firstId_contactName.setText(phoneContact.getDesplayName());
                break;
            case 2:
                PhoneContact phoneContact1 = (PhoneContact) data.getSerializableExtra("phone");
                edit_second_contactName.setText(phoneContact1.getDesplayName());
                put_phone2.setText(phoneContact1.getPhoneNum());
                break;
        }
    }

    class FirstSaveUserInfo1 extends AsyncTask<Map, Void, String> {
        @Override
        protected String doInBackground(Map... params) {
            //第一次保存信息接口
            Message message = new Message();
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/saveEmergencyContact", params[0], ThirdActivity.this);

            if (StringUtils.isBlank(result)) {
                return null;
            }
//            Result<HashMap> resultObject = Result.fromJson(result, HashMap.class);
            return result;
        }

        @Override
        protected void onPreExecute() {
            showWaitDialog();
        }

        @Override
        protected void onPostExecute(String result) {
            closeWaitDialog();
            {
                if (result == null) {
                    CreditXAgent.onSubmit(ActionName.Submit.CONTACT_INFO_SAVE_CONTACTS,
                            CreditXAgent.ActionStatus.FAILED, "提交失败");
                    showShortToast1("连接超时！");
                } else {
                    //请求成功
                    try {
                        JSONObject dataJson = new JSONObject(result);
                        String code = dataJson.optString("code");
                        String msg = dataJson.optString("msg");
//                        showShortToast1(msg);

                        if (Constants.DEFAULT_SUCCESS_CODE.equals(code)) {
                            CreditXAgent.onSubmit(ActionName.Submit.CONTACT_INFO_SAVE_CONTACTS,
                                    CreditXAgent.ActionStatus.SUCCESS, "提交成功");
                            closeWaitDialog();
//                            User loginUser = gson.fromJson(gson.toJson(result.getData().get("user")), User.class);
//                            UserBank userBank = gson.fromJson(gson.toJson(result.getData().get("userBank")), UserBank.class);
//                        UserInfo userInfo = new UserInfo();
//                            String userInfo12 = (String) result.getData().get("userInfo");
//                            UserInfo userInfo= JSON.parseObject(userInfo12,UserInfo.class);
//                            JSONObject  userInfos = dataJson.getJSONObject("data").getJSONObject("userInfo");
                            String userInfoStr = dataJson.getJSONObject("data").optString("userInfo");
                            String userBanks = dataJson.getJSONObject("data").optString("userBank");
                            UserBank userbank = JSON.parseObject(userBanks, UserBank.class);
                            UserInfo userinfo = JSON.parseObject(userInfoStr, UserInfo.class);

//                        UserContacts userContacts = gson.fromJson(gson.toJson(result.getData().get("userContacts")), UserContacts.class);
                            //更新数据库
                            UserBank.deleteAll(UserBank.class);
                            userbank.save();
                            UserInfo.deleteAll(UserInfo.class);
                            userinfo.save();

//                        userContacts.save();
//                            Constants.LOGIN_USER = loginUser;
                            try {
                                String jobState = sharedPreferanceUtils.getJobState();

                                if (!TextUtils.isEmpty(jobState)) {
                                    if (jobState.equals("1") || jobState.equals("2")) {
                                        ThirdActivity.this.finish();
                                    } else {
                                        Intent mainIntent = new Intent(ThirdActivity.this, FourthActivity.class);
                                        startActivity(mainIntent);
                                        ThirdActivity.this.finish();
                                    }


                                } else {
//                            showShortToast1(result.getMsg());
                                }
                            } catch (Exception e) {

                            }

                        } else {
                            CreditXAgent.onSubmit(ActionName.Submit.CONTACT_INFO_SAVE_CONTACTS,
                                    CreditXAgent.ActionStatus.FAILED, "提交失败");
                            showShortToast1(dataJson.optString("msg"));
                            closeWaitDialog();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                closeWaitDialog();
            }
        }
    }
}
